package com.daon.controller;

import com.daon.common.Const;
import com.daon.common.ServerResponse;
import com.daon.service.ISysUserService;
import com.daon.util.VerifyCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author 1daon
 * @EMAIL 532418116@qq.com
 * @Version 创建时间：2019/3/21 14:29 PM
 * @Modified By
 */
@Controller
@RequestMapping("/sys/login")
public class LoginController {

    @Autowired
    private ISysUserService iSysUserService;

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping
    public ModelAndView index(){
        return new ModelAndView("backend/public/login");
    }

    @RequestMapping(value="login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse login(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        return iSysUserService.login(request, response, session);
    }
    @RequestMapping("/relogin.page")
    public ModelAndView relogin(){
        return new ModelAndView("backend/public/relogin");
    }

    @RequestMapping("/logout.page")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        String path = "/sys/login";
        response.sendRedirect(path);
    }

    @RequestMapping(value = "getVerifyCode.do")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字符串
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        //存入Session, 此处可以根据自己的需求
        HttpSession session = request.getSession();
        session.setAttribute(Const.VerifySession.VERIFY_CODE, verifyCode);
        //判断LocalDateTime.now().isAfter(expireTime);
        session.setAttribute(Const.VerifySession.VERIFY_EXPIRE_TIME, LocalDateTime.now().plusSeconds(300));//图形验证码缓存5分钟
        //生成图片
        int w = 100, h = 40;
        try {
            //将图片写入到 response 的输出流即可将图片返回到客户端了
            VerifyCodeUtil.outputImage(w, h, response.getOutputStream(), verifyCode);
        } catch (IOException e) {
            logger.error("生成验证码失败");
        }
    }

}
